﻿using AutoMapper;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using MyBlog.IService;
using MyBlog.Model;
using MyBlog.WebApi.ApiResult;
using MyBlog.WebApi.MD5Tool;
using System;
using System.Threading.Tasks;

namespace MyBlog.WebApi.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    [Authorize]
    public class WriterController : ControllerBase
    {
        private readonly IWriterInfoService  _iWriterInfoService;
        public WriterController(IWriterInfoService iWriterInfoService)
        {
            _iWriterInfoService = iWriterInfoService;
        }

        [AllowAnonymous]
        [HttpGet("WriterInfo")]
        public async Task<ActionResult<ApiResults>> GetWriterInfo([FromServices] IMapper iMapper, int id)
        {
            var writers = await _iWriterInfoService.FindAsync(id);
            if (writers == null)
            {
                return ApiResultsHelper.Error(204, "未查询到数据,数据表为空");
            }
            var writerDTO = iMapper.Map<WriterDTO>(writers);
            return ApiResultsHelper.Success("查询成功", writerDTO);
        }

        [HttpPost("Create")]
        public async Task<ActionResult<ApiResults>> Create(string name,string username,string userpwd)
        {
            WriterInfo writer = new WriterInfo()
            {
                Name = name,
                UserName = username,
                UserPwd = MD5Helper.MD5Encryption(userpwd)//MD5加密
            };
            var temp = await _iWriterInfoService.FindAsync(c => c.UserName == username);
            if(temp != null)
            {
                return ApiResultsHelper.Error(500, "账号已存在");
            }
            bool res = await _iWriterInfoService.CreateAsync(writer);
            if (!res)
            {
                return ApiResultsHelper.Error(500, "创建数据失败");
            }
            return ApiResultsHelper.Success(201, "创建数据成功");
        }

        [HttpDelete("Delete")]
        public async Task<ActionResult<ApiResults>> Delete(int id)
        {
            bool res = await _iWriterInfoService.DeleteAsync(id);
            if (!res)
            {
                return ApiResultsHelper.Error(500, "删除数据失败");
            }
            return ApiResultsHelper.Success("删除数据成功");
        }

        [HttpPut("Edit")]
        public async Task<ApiResults> Edit(string name)
        {
            int id = Convert.ToInt32(this.User.FindFirst("Id").Value);
            var writer = await _iWriterInfoService.FindAsync(id);
            writer.Name = name;
            bool b = await _iWriterInfoService.EditAsync(writer);
            if (!b) return ApiResultsHelper.Error("修改失败");
            return ApiResultsHelper.Success("修改成功");
        }
    }
}
